package uml.util;

import java.awt.Component;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.awt.print.PrinterJob;

import javax.swing.RepaintManager;



/**
 * This class implements a printer for any JComponent. It's primary purpose is
 * to print the <tt>DiagramPanel</tt>.
 * 
 * @author Rick Myers
 * 
 */
public class UMLPrinter
		implements Printable
{
	//The component to be printed.
	private Component printableObject;

	/**
	 * Default constructor for <tt>UMLPrinter</tt>. The printer can not be used
	 * without being passed something to print.
	 * 
	 * @param objectToBePrinted
	 */
	public UMLPrinter (Component objectToBePrinted)
	{
		printableObject = objectToBePrinted;
	}

	/**
	 * Attempts printing the print job.
	 */
	public void print ()
	{
		PrinterJob printer = PrinterJob.getPrinterJob ();
		printer.setPrintable (this);
		if (printer.printDialog ())
			try
			{
				printer.print ();
			}
			catch (PrinterException exception)
			{
				System.out.println ("Failed Printing - " + exception);
			}
	}

	/**
	 * Calls the objects paint method.
	 * 
	 * @param printableObject
	 */
	public static void printComponent (Component printableObject)
	{
		new UMLPrinter (printableObject).print ();
	}

	/**
	 * This overrides print method of <tt>Printable</tt>. It takes care of
	 * disabling buffering so that print jobs are of a higher quality. The
	 * buffer is enabled after painting is complete.
	 */
	@Override
	public int print (Graphics graphics, PageFormat pageFormat, int pageIndex)
			throws PrinterException
	{
		if (pageIndex > 0)
		{
			return (NO_SUCH_PAGE);
		}
		else
		{
			Graphics2D g = (Graphics2D) graphics;
			//Gets the current paint manager of the printable swing component
			RepaintManager paintManager = RepaintManager.currentManager (printableObject);
			//Converts printable object coordinates to paper coordinates.
			g.translate (pageFormat.getImageableX (), pageFormat.getImageableY ());
			paintManager.setDoubleBufferingEnabled (false);
			printableObject.paint (g);
			paintManager.setDoubleBufferingEnabled (true);
			return (PAGE_EXISTS);
		}
	}
}
